
#include <iostream>
#include <fstream>
#include "extramethods.h"



#include "Scenario.h"

using std::string;
using std::cout;
using std::endl;
using std::ifstream;

hash_map<string, vector<string>* > Scenario::_filesHm;

Scenario::Scenario(string filename) : _filename(filename)
{
    _line =-1;
    readFile();
}

Scenario::~Scenario()
{
    // delete _text is not needed as the _text contence will be deleted by last instance
    // if last instance of class, then empty the _files hash_map and delete the contence of the texts
    // this is not done and causes a small memory leak
    // this is allowed by us for performance reasons
}

void Scenario::readFile()
{
    // if ( ! filename in hash_map) {
    //   read file => into _text vector
    //   put in hash_map
    // }
    // else {
    //   set _text = pointer of hash_map
    // }
    // FIXME TODO add locking here !!! multiple threads might be trying to open the file at the same time...
    // TODO is this really needed ? in practice not, but it'd be better
    if ( '\0' == _filesHm[_filename] )
    {
        _text = new vector<string>;
        _text->clear();
        string *lineContent = new string();
        ifstream *textstream = new ifstream(_filename.c_str());
        if ((*textstream).good())
        {
            while (getline(*textstream, *lineContent)) {
                string st =  stripWhiteSpaces(*lineContent);
                if(st!=""){ //for detecting an empty line
                    char ch = st.at(0);
                    if(ch != '#' ) { 
                        _text->push_back(*lineContent);
                    }
                }
            }
        }
        else std::cerr << "Cannot read file: " << _filename << std::endl;
        textstream->close();

        delete lineContent;
        delete textstream;

        // insert vector into hash_map
        _filesHm[_filename] = _text;
    }
    else {
        // get vector out of hash_map
        _text = _filesHm[_filename];
    }
}

int Scenario::getSize()
{
    return _text->size();
}

string Scenario::getNextLine()
{
    if(hasNextLine())
    {
        return _text->at(++_line);
    }
    return "";
}

bool Scenario::hasNextLine()
{
    if(_line+1 < _text->size())
    {
        return true;
    }
    return false;
}

string Scenario::getFirstLine()
{
    return _text->front() ;
}

string Scenario::getLastLine()
{
    return _text->back() ;
}
